import React from 'react';
import ReactDom from 'react-dom';
import {Form,Input,Checkbox,Button,Modal,Table,message} from 'antd';
import util from 'util';
import filter from 'filter';
import { hashHistory } from 'react-router';
const FormItem = Form.Item;
const confirm = Modal.confirm;
import {Search,Edit,FuncTree,TreeSelectDemo,MergeOrg} from './components/orgform.js';

class User extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            visible : false,
            key : "111",
            searchParams:{},
            listdata:[],
            operation:'',
            orgOprateStr:'',
            isLoading:false,
            expandedRowKeys:[],
            add:false,
            edit:false,
            setting:false,
            searchWithCondition:false,
            mergeVisible:false              // 合并显示
        };
        this.openKey=[];
        this.loadKey=[];
    }
    componentDidMount(){
        var oprates=util.getLocalObj("roleids");
        // var oprates=["412","411"];
        if(oprates[0]=="SYSTEM"){
            this.setState({
                add:true,
                edit:true,
                setting:true
            });
        }
        else{
            for(var i=0;i<oprates.length;i++){
                switch (oprates[i]){
                    case "411":
                        this.setState({
                            add:true
                        });
                        break;
                    case "412":
                        this.setState({
                            edit:true
                        });
                        break;
                    case "413":
                        this.setState({
                            setting:true
                        });
                        break;
                }
            }
        }

        // 界面初始化2423wesd23sdf23
        this.refresh({orgno: "", orgname: "",parentorgno:""});
    }
    setChildren(listData,indexlist,childrenData){
        var j=indexlist[0];
        if(indexlist.length>1){
            indexlist.splice(0,1);
            this.setChildren(listData[j].children,indexlist,childrenData);
        }else{
            console.log("打印需要打印数据sd45");
            console.log(listData[j]);
            //12
            listData[j].children=childrenData;
        }
    }

    onSelect(record) {
        return;
        if(this.state.searchWithCondition){
            return;
        }

        if(!record.children){
            return;
        }
        var have = true;
        //

        for(var m=0;m<this.openKey.length;m++){
            if(this.loadKey[m]==record.key){
                have = false;
                return;
            }
        }
        // werfqwerqw
        console.log("key:",this.loadKey);
        // let keyvalue=record.key;
        this.loadKey.push(record.key);

        console.log("不小心点击到列表行");
        var paramsvar={};
        paramsvar=this.state.searchParams;
        paramsvar.parentorgno=record.orgno;
        paramsvar.orgno="";
        paramsvar.orgname="";
        // 刷新列表数据
        util.httpRequest({type:"POST",url:'org010101.json',params:paramsvar,success:function(result){
            var currentindex= record.index.slice();
            //let indexs=record.index.slice
            var list=this.state.listdata;
            if(result.rows){
                for(var i=0;i<result.rows.length;i++){
                    let indexs=record.index.slice();
                    if(result.rows[i].isleaf=="false"){
                        result.rows[i].children=[];
                    }
                    indexs.push(i);
                    result.rows[i].index=indexs;
                }
            }
            if(result.rows&&result.rows.length>0){
                this.setChildren(list,currentindex,result.rows);
            }

            console.log(list);
            this.setState({
                listdata:list
            });
            this.openKey.push(record.key);
        }.bind(this)});
    }
    expandedRowRender(record, selected){
        console.log(record);
        console.log("expand"+record+selected);
    }

    // 合并机构  
    mergeOrg(record){
        this.setState({
            mergeVisible:true,
            data:record,
        });
    }

    // 删除机构
    deleteOrg(record){
        confirm({
            title: '您是否确认要删除该机构',
            content: "",
            onOk: function () {
                util.httpRequest({
                    type: "POST",
                    url: 'org010108.json',
                    params: {"orgno": record.orgno},
                    success: function (result) {
                        // 刷新列表
                        this.refresh({orgno: "", orgname: "",parentorgno:""});
                    }.bind(this)
                });
            }.bind(this)
        });
    }

    //
    config(){
        var me = this;
        return {
            searchconfig : {
                search:this.search.bind(this)
            },
            table : {
                // expandedRowRender:this.expandedRowRender.bind(this),
                // expandedRowKeys:this.state.expandedRowKeys,
                key :this.state.key,
                loading:this.state.isLoading,
                pagination:false,
                dataSource : this.state.listdata,
                columns :
                    [{
                        title : "机构代码",
                        dataIndex : "orgno",
                        key : "orgno",
                        width: '15%'
                    },{
                        title : "机构名称",
                        dataIndex : "orgname",
                        key : "orgname",
                        width: '15%'
                    },{
                        title : "机构级别",
                        dataIndex : "orglevel",
                        key : "orglevel",
                        render : function (value,data,rowIndex) {
                            var str=util.convert("orglevel",value);
                            return str;
                        },
                        width: '10%'
                    },{
                        title : "上级机构",
                        dataIndex : "parentorgname",
                        key : "parentorgname",
                        width: '15%'
                    },{
                        title : "机构状态",
                        dataIndex : "org_status",
                        key : "org_status",
                        render:function(value,data,rowIndex){
                            console.log("机构状态"+value);
                            var str=util.convert("org_status",value);
                            return str;
                        },
                        width: '10%'
                    },{
                        title: '机构操作',
                        key: 'operation',
                        width: '25%',
                        render: (text, record,index) => (
                            <span>
                                {this.state.edit ?
                                   <a className="a-operate" onClick={this.edit.bind(this,record,index)}>修改</a> : null}
                                {this.state.edit ?
                                <span
                                    className="ant-divider"></span>: null}
                                {this.state.setting ?
                                    <a className="a-operate" onClick={this.oprateOrgState.bind(this,record,"1")}
                                       disabled={record.org_status=="C"}>停用</a> : null}
                                {this.state.setting ?<span
                                     className="ant-divider"></span>: null}
                                {this.state.setting ?
                                    <a className="a-operate" onClick={this.oprateOrgState.bind(this,record,"0")}
                                       disabled={record.org_status=='N'}>启用</a> : null}
                                <span className="ant-divider"></span>
                                <a className="a-operate" onClick={this.deleteOrg.bind(this,record)}>删除</a>
                                <a className="a-operate" onClick={this.mergeOrg.bind(this,record)}>撤并</a>
                            </span>
                        )
                    }
                ]
            },
            modal : {
                visible  : this.state.visible,
                onOk : function(){
                    me.hide();
                },
                onCancel : function(){
                    me.hide();
                },
                title : this.state.title,
                children : React.createElement(Edit,{
                    operation:this.state.operation,
                    key : this.state.key,
                    data : this.state.data,
                    ref : "form",
                    isAdd:this.state.isAdd
                })
            },
            mergeModal : {
                visible  : this.state.mergeVisible,
                onOk : function(){
                    me.hide();
                },
                onCancel : function(){
                    me.hide();
                },
                title : "撤并机构",
                children : React.createElement(MergeOrg,{
                    operation:this.state.operation,
                    key : Math.random(),
                    data : this.state.data,
                    ref:"mergeForm"
                })
            },
            btn : {
                type:"primary" ,
                className:"addBtn",
                children : "+  新增",
                onClick : function () {
                    me.show();
                    me.setState({
                        key : Math.random(),
                        title:"新增机构",
                        data : {
                            account : "123"
                        },
                        isAdd:true,
                        operation:"create"
                    },function () {
                        var {setFieldsValue} = me.refs.form.getForm();
                        // console.log(me.refs);
                        setFieldsValue({

                            account : "aaa"
                        })
                    })
                }
            },
            exportBtn: {
                children: "导出",
                style: {marginTop: 10, marginBottom: 10},
                onClick: function () {
                    window.open(util.baseUrl+"platform/orgcsv.json?export_param=1");
                }
            },
            mergeBtn:{
                children:'合并',
                style: {marginTop: 10, marginBottom: 10},
                onClick:function () {

                }
            }
        }
    }

    /*-----展开行触发-----*/
    expandFun(expanded, record){
        console.log("")
        if(this.state.searchWithCondition){
            return;
        }

        if(!record.children){
            return;
        }
        console.log("开始展开洛sadfasdf223421341");
        var have = true;

        for(var m=0;m<this.openKey.length;m++){
            if(this.loadKey[m]==record.key){
                have = false;
                return;
            }
        }
        //asdasklasdsaasdsa
        console.log("key:",this.loadKey);
        // let keyvalue=record.key;
        this.loadKey.push(record.key);

        console.log("不小心点击到列表行");
        var paramsvar={};
        paramsvar=this.state.searchParams;
        paramsvar.parentorgno=record.orgno;
        paramsvar.orgno="";
        paramsvar.orgname="";
        // 刷新列表数据dfsd
        util.httpRequest({type:"POST",url:'org010101.json',params:paramsvar,success:function(result){
            var currentindex= record.index.slice();
            //let indexs=record.index.slice();sd
            var list=this.state.listdata;
            if(result.rows){
                for(var i=0;i<result.rows.length;i++){
                    let indexs=record.index.slice();
                    if(result.rows[i].isleaf=="false"){
                        result.rows[i].children=[];
                    }
                    indexs.push(i);
                    result.rows[i].index=indexs;
                }
            }
            if(result.rows&&result.rows.length>0){
                this.setChildren(list,currentindex,result.rows);
            }

            console.log(list);
            this.setState({
                listdata:list
            });
            this.openKey.push(record.key);
        }.bind(this)});
    }

    oprateOrgState(record,type,e){
        console.log(record);
        var params={};
        params.orgid=record.orgid;
        //params.org_status=type;
        if(type==0){
            params.org_status = "N"
        }
        if(type==1){
            params.org_status = "C"
        }
        console.log(this.state.searchParams);

        // 刷新列表数据
        util.httpRequest({type:"POST",url:'org010104.json',params:params,success:function(result){
            if(result.ret_code=="0000"){
                message.success(result.ret_msg);
            }else{
                return;
            }

            if(record.org_status=="N"){
                record.org_status="C";
            }else{
                record.org_status="N";
            }

            var list=this.state.listdata;
            let indexs=record.index.slice();

            this.updateRecord(list,indexs,record);
            // console.log(list);
            this.setState({
                listdata:list
            });
        }.bind(this)});
        e.stopPropagation();
    }
    edit(record,index,e){
        console.log(record);
        var i = Math.random();
        this.setState({
            title:"修改机构",
            data:record,
            visible:true,
            key:i,
            operation:'edit',
            isAdd:false,
        });
        e.stopPropagation();
    }
    search(values){
        console.debug("查询 1sdc");
        this.setState({
            searchParams:values
        });

        // 打开等待框
        this.refresh(values);
    }
    refresh(values){
        var flag=false;
        if(values.orgname!=""||values.orgno!=""){
            flag=true;
        }
        this.setState({
            isLoading:true,
            searchWithCondition:flag
        });
        // 刷新列表数据
        util.httpRequest({router:this.props.router,type:"POST",url:'org010101.json',params:values,success:function(result){
            console.log(result+"sd23sd23sf");
            // this.props.router.push('login');
            // sshashHistory.push("login");
            // this.props.router.push("main/org")
            var list=[];
            if(result.rows){
                for(var i=0;i<result.rows.length;i++){
                    result.rows[i].index=[i];
                    if(result.rows[i].isleaf=="false"&&!flag){
                        result.rows[i].children=[];
                    }
                    list.push(result.rows[i].key);
                    //result.rows[i].isleaf=false;
                }
            }
            console.log(result.rows);

           var i=  Math.random();
            this.openKey=[];
            this.loadKey=[];

            this.setState({
                listdata:result.rows,
                isLoading:false,
                expandedRowKeys:[],
                key :i
            });
        }.bind(this)});
    }
    show(){
        this.setState({
            visible : true
        })
    }
    hide(){
        this.setState({
            visible : false,
            mergeVisible:false
        })
    }
    login(data){
        console.log(data+"1");
    }
    onSave(){
        var form=this.refs.form.getForm();
        form.validateFields((errors,values)=>{
            if(!!errors){
                return;
            }
            console.log(values);


            if(this.state.operation=="edit"){
                this.update(this.state.data,values);
            }
            else{
                this.create(values);
            }
        });
    }
    // 修改机构
    update(record,values){
        values.orgid=record.orgid;
        values.orgno=record.orgno;
        // 修改机构信息
        util.httpRequest({type:"POST",url:'org010103.json',params:values,success:function(result){
            if( result.ret_code!="0000"){
                return;
            }
            record.orgname=values.orgname;
            record.orglevel=values.orglevel;
            record.lat=values.lat;
            record.lng=values.lng;

            var list=this.state.listdata;
            let indexs=record.index.slice();

            this.updateRecord(list,indexs,record);
            console.log(list);
            // 关闭弹出框
            this.setState({
                listdata:list,
                visible:false
            });
        }.bind(this)});
    }
    updateRecord(listData,indexlist,childrenData){
        console.log("开始indexs");
        console.log(indexlist);
        var j=indexlist[0];
        if(indexlist.length>1){
            indexlist.splice(0,1);
            this.updateRecord(listData[j].children,indexlist,childrenData);
        }else{
            console.log("打印需要2s");
            console.log(listData[j]);
            //12
            listData[j]=childrenData;
        }
    }
    create(searchValues){
        // 待修改1312qw
        //if(searchValues.parentorgno==undefined||searchValues.parentorgno==""){
        //    searchValues.parentorgno="ROOT";
        //}
        // 调用新增接口
        util.httpRequest({type:"POST",url:'org010102.json',params:searchValues,success:function(result){
            console.log("新增数据s：",result);
            // 关闭弹出框
            this.setState({
                visible:false
            });
            this.refresh({orgno: "", orgname: "",parentorgno:""});
        }.bind(this)});
    }
    expandedRowRender(){
        console.log("expander");
    }

    // 保存合并 werwqer
    onSaveMerge(){
        var form=this.refs.mergeForm.getForm();
        form.validateFields((errors,values)=>{
            if(!!errors){
                return;
            }
            console.log("merge:",values);
            values.being_orgno=this.state.data.orgno;
            values.merge_orgno=values.parentorgno;
            // this.state.data.
            // 调用新增接口
            util.httpRequest({type:"POST",url:'org010109.json',params:values,success:function(result){
                console.log("新增数据s：",result);
                // 关闭弹出框
                this.setState({
                    mergeVisible:false
                });
                this.refresh({orgno: "", orgname: "",parentorgno:""});
            }.bind(this)});
        });
    }

    render(){
        var config = this.config();
        const rowSelection = {
            onChange(selectedRowKeys, selectedRows) {
                console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
            },
            onSelect(record, selected, selectedRows) {
                console.log(record, selected, selectedRows);
            },
            onSelectAll(selected, selectedRows, changeRows) {
                console.log(selected, selectedRows, changeRows);
            },
        };

        return (
            <div>
                <Search {...config.searchconfig}></Search>
                <Modal {...config.modal} closable={false}  footer={[
                        <Button key="back" type="ghost" size="large" onClick={this.hide.bind(this)}>取消</Button>,
                        <Button key="submit" type="primary" size="large" onClick={this.onSave.bind(this)}>保存</Button>
                   ]} >
                </Modal>
                <Modal {...config.mergeModal} closable={false}  footer={[
                        <Button key="back" type="ghost" size="large" onClick={this.hide.bind(this)}>取消</Button>,
                        <Button key="submit" type="primary" size="large" onClick={this.onSaveMerge.bind(this)}>保存</Button>
                   ]} >
                </Modal>
                {this.state.add? <Button {...config.btn}></Button>:null}
                <Button {...config.exportBtn}></Button>
                <Table {...config.table} defaultExpandedRowKeys={this.openKey}  onRowClick={this.onSelect.bind(this)} onExpand ={this.expandFun.bind(this)}></Table>
            </div>
        );
    }
}

User.contextTypes = {
    router: React.PropTypes.object
};

export default User;


